import 'package:flutter/material.dart';
import 'package:toastification/toastification.dart';

/// 进度任务Toast工具类
/// 专门用于显示分步骤执行的耗时任务进度
class ProgressToastUtils {
  static ToastificationItem? _currentProgressToast;

  /// 开始显示进度任务
  static ToastificationItem startProgressTask(
    BuildContext context, {
    required String taskName,
    required List<String> steps,
    VoidCallback? onCancel,
  }) {
    // 如果已有进度Toast，先关闭
    if (_currentProgressToast != null) {
      toastification.dismiss(_currentProgressToast!);
    }

    _currentProgressToast = toastification.showCustom(
      context: context,
      alignment: Alignment.topLeft,
      autoCloseDuration: null, // 手动控制关闭
      animationBuilder: (context, animation, alignment, child) {
        return SlideTransition(
          position: Tween<Offset>(
            begin: const Offset(-1.0, 0.0),
            end: Offset.zero,
          ).animate(CurvedAnimation(
            parent: animation,
            curve: Curves.easeOutCubic,
          )),
          child: FadeTransition(
            opacity: animation,
            child: child,
          ),
        );
      },
      builder: (context, holder) {
        return _ProgressTaskWidget(
          taskName: taskName,
          steps: steps,
          onCancel: onCancel != null ? () {
            onCancel();
            toastification.dismiss(holder);
            _currentProgressToast = null;
          } : null,
          onDismiss: () {
            toastification.dismiss(holder);
            _currentProgressToast = null;
          },
        );
      },
    );

    return _currentProgressToast!;
  }

  /// 更新进度
  static void updateProgress({
    required int currentStep,
    required String stepDescription,
    String? additionalInfo,
  }) {
    // 通过全局状态管理更新进度
    _ProgressTaskNotifier.instance.updateProgress(
      currentStep: currentStep,
      stepDescription: stepDescription,
      additionalInfo: additionalInfo,
    );
  }

  /// 完成任务
  static void completeTask(
    BuildContext context, {
    required String completionMessage,
    Duration? showDuration,
  }) {
    if (_currentProgressToast != null) {
      toastification.dismiss(_currentProgressToast!);
      _currentProgressToast = null;
    }

    // 显示完成提示
    toastification.showCustom(
      context: context,
      alignment: Alignment.topLeft,
      autoCloseDuration: showDuration ?? const Duration(seconds: 3),
      animationBuilder: (context, animation, alignment, child) {
        return ScaleTransition(
          scale: Tween<double>(begin: 0.8, end: 1.0).animate(
            CurvedAnimation(parent: animation, curve: Curves.elasticOut),
          ),
          child: FadeTransition(opacity: animation, child: child),
        );
      },
      builder: (context, holder) {
        return Container(
          margin: const EdgeInsets.all(16),
          padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [
                Colors.green.withOpacity(0.9),
                Colors.green.shade600.withOpacity(0.8),
              ],
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
            ),
            borderRadius: BorderRadius.circular(16),
            boxShadow: [
              BoxShadow(
                color: Colors.green.withOpacity(0.3),
                blurRadius: 20,
                spreadRadius: 0,
                offset: const Offset(0, 6),
              ),
            ],
          ),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Container(
                width: 28,
                height: 28,
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(14),
                ),
                child: const Icon(
                  Icons.check_rounded,
                  color: Colors.green,
                  size: 18,
                ),
              ),
              const SizedBox(width: 12),
              Flexible(
                child: Text(
                  completionMessage,
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 15,
                    fontWeight: FontWeight.w600,
                    letterSpacing: 0.5,
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  /// 任务失败
  static void failTask(
    BuildContext context, {
    required String errorMessage,
    VoidCallback? onRetry,
  }) {
    if (_currentProgressToast != null) {
      toastification.dismiss(_currentProgressToast!);
      _currentProgressToast = null;
    }

    toastification.showCustom(
      context: context,
      alignment: Alignment.topLeft,
      autoCloseDuration: const Duration(seconds: 5),
      builder: (context, holder) {
        return Container(
          margin: const EdgeInsets.all(16),
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [
                Colors.red.withOpacity(0.9),
                Colors.red.shade600.withOpacity(0.8),
              ],
            ),
            borderRadius: BorderRadius.circular(16),
            boxShadow: [
              BoxShadow(
                color: Colors.red.withOpacity(0.3),
                blurRadius: 20,
                offset: const Offset(0, 6),
              ),
            ],
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  const Icon(Icons.error_rounded, color: Colors.white, size: 20),
                  const SizedBox(width: 8),
                  Flexible(
                    child: Text(
                      errorMessage,
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 14,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                ],
              ),
              if (onRetry != null) ...[
                const SizedBox(height: 12),
                ElevatedButton.icon(
                  onPressed: () {
                    toastification.dismiss(holder);
                    onRetry();
                  },
                  icon: const Icon(Icons.refresh, size: 16),
                  label: const Text('重试'),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.white,
                    foregroundColor: Colors.red,
                    padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                  ),
                ),
              ],
            ],
          ),
        );
      },
    );
  }

  /// 清除当前进度Toast
  static void clearProgress() {
    if (_currentProgressToast != null) {
      toastification.dismiss(_currentProgressToast!);
      _currentProgressToast = null;
    }
  }
}

/// 进度任务状态管理
class _ProgressTaskNotifier extends ChangeNotifier {
  static final _ProgressTaskNotifier _instance = _ProgressTaskNotifier._internal();
  static _ProgressTaskNotifier get instance => _instance;
  _ProgressTaskNotifier._internal();

  int _currentStep = 0;
  int _totalSteps = 0;
  String _stepDescription = '';
  String _additionalInfo = '';
  List<String> _steps = [];

  int get currentStep => _currentStep;
  int get totalSteps => _totalSteps;
  String get stepDescription => _stepDescription;
  String get additionalInfo => _additionalInfo;
  List<String> get steps => _steps;
  double get progress => _totalSteps > 0 ? _currentStep / _totalSteps : 0.0;
  int get progressPercentage => (progress * 100).round();

  void initializeTask(List<String> steps) {
    _steps = steps;
    _totalSteps = steps.length;
    _currentStep = 0;
    _stepDescription = steps.isNotEmpty ? steps[0] : '';
    _additionalInfo = '';
    notifyListeners();
  }

  void updateProgress({
    required int currentStep,
    required String stepDescription,
    String? additionalInfo,
  }) {
    _currentStep = currentStep;
    _stepDescription = stepDescription;
    _additionalInfo = additionalInfo ?? '';
    notifyListeners();
  }
}

/// 进度任务Widget
class _ProgressTaskWidget extends StatefulWidget {
  final String taskName;
  final List<String> steps;
  final VoidCallback? onCancel;
  final VoidCallback onDismiss;

  const _ProgressTaskWidget({
    required this.taskName,
    required this.steps,
    this.onCancel,
    required this.onDismiss,
  });

  @override
  State<_ProgressTaskWidget> createState() => _ProgressTaskWidgetState();
}

class _ProgressTaskWidgetState extends State<_ProgressTaskWidget>
    with TickerProviderStateMixin {
  late AnimationController _progressController;
  late AnimationController _pulseController;

  @override
  void initState() {
    super.initState();
    
    _progressController = AnimationController(
      duration: const Duration(milliseconds: 800),
      vsync: this,
    );
    
    _pulseController = AnimationController(
      duration: const Duration(milliseconds: 1500),
      vsync: this,
    )..repeat(reverse: true);

    // 初始化任务状态
    _ProgressTaskNotifier.instance.initializeTask(widget.steps);
    _ProgressTaskNotifier.instance.addListener(_onProgressUpdate);
  }

  @override
  void dispose() {
    _ProgressTaskNotifier.instance.removeListener(_onProgressUpdate);
    _progressController.dispose();
    _pulseController.dispose();
    super.dispose();
  }

  void _onProgressUpdate() {
    if (mounted) {
      final progress = _ProgressTaskNotifier.instance.progress;
      _progressController.animateTo(progress);
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    final notifier = _ProgressTaskNotifier.instance;
    
    return Container(
      width: 320,
      margin: const EdgeInsets.all(16),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [
            Colors.blueGrey.shade800.withOpacity(0.95),
            Colors.blueGrey.shade700.withOpacity(0.9),
          ],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.circular(20),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.3),
            blurRadius: 25,
            spreadRadius: 0,
            offset: const Offset(0, 10),
          ),
          BoxShadow(
            color: Colors.blueGrey.withOpacity(0.1),
            blurRadius: 5,
            spreadRadius: 0,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 头部：任务名称和百分比
          Row(
            children: [
              Expanded(
                child: Text(
                  widget.taskName,
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 16,
                    fontWeight: FontWeight.w700,
                    letterSpacing: 0.5,
                  ),
                ),
              ),
              AnimatedBuilder(
                animation: _pulseController,
                builder: (context, child) {
                  return Container(
                    padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                    decoration: BoxDecoration(
                      color: Colors.blue.withOpacity(0.2 + 0.1 * _pulseController.value),
                      borderRadius: BorderRadius.circular(15),
                      border: Border.all(
                        color: Colors.blue.withOpacity(0.5),
                        width: 1,
                      ),
                    ),
                    child: Text(
                      '${notifier.progressPercentage}%',
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 14,
                        fontWeight: FontWeight.w600,
                        letterSpacing: 0.5,
                      ),
                    ),
                  );
                },
              ),
              if (widget.onCancel != null) ...[
                const SizedBox(width: 12),
                GestureDetector(
                  onTap: widget.onCancel,
                  child: Container(
                    padding: const EdgeInsets.all(6),
                    decoration: BoxDecoration(
                      color: Colors.white.withOpacity(0.1),
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: const Icon(
                      Icons.close,
                      color: Colors.white70,
                      size: 16,
                    ),
                  ),
                ),
              ],
            ],
          ),
          
          const SizedBox(height: 16),
          
          // 进度条
          Container(
            height: 6,
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.2),
              borderRadius: BorderRadius.circular(3),
            ),
            child: AnimatedBuilder(
              animation: _progressController,
              builder: (context, child) {
                return FractionallySizedBox(
                  alignment: Alignment.centerLeft,
                  widthFactor: _progressController.value,
                  child: Container(
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        colors: [
                          Colors.blue.shade400,
                          Colors.blue.shade600,
                        ],
                      ),
                      borderRadius: BorderRadius.circular(3),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.blue.withOpacity(0.4),
                          blurRadius: 6,
                          spreadRadius: 0,
                        ),
                      ],
                    ),
                  ),
                );
              },
            ),
          ),
          
          const SizedBox(height: 12),
          
          // 步骤信息
          Text(
            '步骤 ${notifier.currentStep}/${notifier.totalSteps}',
            style: TextStyle(
              color: Colors.white.withOpacity(0.7),
              fontSize: 12,
              fontWeight: FontWeight.w500,
            ),
          ),
          
          const SizedBox(height: 6),
          
          // 当前步骤描述
          AnimatedSwitcher(
            duration: const Duration(milliseconds: 300),
            child: Text(
              notifier.stepDescription,
              key: ValueKey(notifier.stepDescription),
              style: const TextStyle(
                color: Colors.white,
                fontSize: 14,
                fontWeight: FontWeight.w500,
                height: 1.3,
              ),
            ),
          ),
          
          // 附加信息
          if (notifier.additionalInfo.isNotEmpty) ...[
            const SizedBox(height: 6),
            AnimatedSwitcher(
              duration: const Duration(milliseconds: 300),
              child: Text(
                notifier.additionalInfo,
                key: ValueKey(notifier.additionalInfo),
                style: TextStyle(
                  color: Colors.white.withOpacity(0.8),
                  fontSize: 12,
                  fontStyle: FontStyle.italic,
                ),
              ),
            ),
          ],
        ],
      ),
    );
  }
}
